from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.models.permission import Permission as PermissionModel, PermissionInDB
from app.schemas.permission import Permission as PermissionSchema, PermissionCreate, PermissionUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/permissions", tags=["权限管理"])

@router.post("/create", response_model=APIResponse[PermissionSchema])
def create_permission(permission: PermissionCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating permission with perm_code: {permission.perm_code}")
    
    # 检查权限编码是否已存在
    db_permission = db.query(PermissionModel).filter(PermissionModel.perm_code == permission.perm_code).first()
    if db_permission:
        logger.warning(f"Permission code already registered: {permission.perm_code}")
        return error_response(message="Permission code already registered", code=400)
    
    # 创建新权限
    db_permission = PermissionModel(
        perm_code=permission.perm_code,
        perm_name=permission.perm_name,
        perm_type=permission.perm_type,
        parent_id=permission.parent_id,
        resource_path=permission.resource_path,
        status=permission.status,
        sort_order=permission.sort_order,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_permission)
    db.commit()
    db.refresh(db_permission)
    
    # 转换为Pydantic模型
    permission_response = PermissionInDB.model_validate(db_permission)
    
    logger.info(f"Permission created successfully with ID: {db_permission.id}")
    return success_response(data=permission_response, message="Permission created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[PermissionSchema]])
def read_permissions(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching permissions with skip: {skip}, limit: {limit}")
    
    permissions = db.query(PermissionModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    permissions_response = [PermissionInDB.model_validate(permission) for permission in permissions]
    total = db.query(PermissionModel).count()
    
    logger.info(f"Found {len(permissions)} permissions")
    return paginated_response(
        items=permissions_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{permission_id}", response_model=APIResponse[PermissionSchema])
def read_permission(permission_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching permission with ID: {permission_id}")
    
    db_permission = db.query(PermissionModel).filter(PermissionModel.id == permission_id).first()
    if db_permission is None:
        logger.warning(f"Permission not found with ID: {permission_id}")
        return error_response(message="Permission not found", code=404)
    
    # 转换为Pydantic模型
    permission_response = PermissionInDB.model_validate(db_permission)
    
    logger.info(f"Permission found with ID: {permission_id}")
    return success_response(data=permission_response)

@router.put("/{permission_id}", response_model=APIResponse[PermissionSchema])
def update_permission(permission_id: int, permission: PermissionUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating permission with ID: {permission_id}")
    
    db_permission = db.query(PermissionModel).filter(PermissionModel.id == permission_id).first()
    if db_permission is None:
        logger.warning(f"Permission not found with ID: {permission_id}")
        return error_response(message="Permission not found", code=404)
    
    # 更新权限信息
    update_data = permission.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_permission, key, value)
    
    db_permission.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_permission)
    
    # 转换为Pydantic模型
    permission_response = PermissionInDB.model_validate(db_permission)
    
    logger.info(f"Permission updated successfully with ID: {permission_id}")
    return success_response(data=permission_response, message="Permission updated successfully")

@router.delete("/{permission_id}", response_model=APIResponse[None])
def delete_permission(permission_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting permission with ID: {permission_id}")
    
    db_permission = db.query(PermissionModel).filter(PermissionModel.id == permission_id).first()
    if db_permission is None:
        logger.warning(f"Permission not found with ID: {permission_id}")
        return error_response(message="Permission not found", code=404)
    
    db.delete(db_permission)
    db.commit()
    
    logger.info(f"Permission deleted successfully with ID: {permission_id}")
    return success_response(message="Permission deleted successfully")
